import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:pitchertools/common/extensions/datetime_extension.dart';
import 'package:pitchertools/dao/data_manager.dart';
import 'package:pitchertools/http/api.dart';
import 'package:pitchertools/http/dio_http.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import 'package:velocity_x/velocity_x.dart';

import '../../../../models/fans_query_bean.dart';
import '../../index.dart';

class LoginDamaiDialog extends GetView<QueryFansController> {
  LoginDamaiDialog({super.key}) {}

  final controller = Get.find<QueryFansController>();

  final TextEditingController codeTEC = TextEditingController();

  /// 构建下拉菜单
  buildDropdownMenuItems() {
    List accountMsgs = controller.state.accountMsgsRx.value;
    var selectedAccountMsg = controller.state.selectedAccountMsg;

    // print(fansQueryApiList);

    List<DropdownMenuItem> dropdownMenuItems = [];

    for (var i = 0; i < accountMsgs.length; i++) {
      var item = DropdownMenuItem(
        value: accountMsgs[i],
        child: Text(accountMsgs[i]['name']),
      );
      dropdownMenuItems.add(item);
    }

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black, width: 1.0),
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: DropdownButton(
        value: selectedAccountMsg['name'] == null ? null : selectedAccountMsg,
        onChanged: (newValue) {
          //设置
          controller.state.selectedAccountMsg = newValue;
          print(newValue);
        },
        items: dropdownMenuItems,
        hint: const Text("请选择账号类型"),
        underline: Container(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('登录大麦').center(),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          //设置间隔为8
          children: [
            15.heightBox,
            Obx(() => buildDropdownMenuItems()),
            10.heightBox,
            Obx(() {
              var imgByteData = controller.state.imgByteData;
              if (imgByteData == "") {
                return GFButton(
                    text: "获取验证码",
                    onPressed: () async {
                      controller.getLoginImgByteData();
                    });
              }
              final byteData = base64Decode(controller.state.imgByteData);
              return Image.memory(byteData).onTap(() {
                controller.getLoginImgByteData();
              });
            }),
            10.heightBox,
            GFTextField(
              controller: codeTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "验证码",
              ),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('登录'),
          onPressed: () async {
            // 验证码
            var code = codeTEC.text.trim();
            // 账号信息
            var accountMsg = controller.state.selectedAccountMsg;
            // uuid
            var uuid = controller.state.loginUUID;
            if (code.isEmpty ||
                uuid.isEmpty ||
                accountMsg == null ||
                accountMsg['userName'] == null) {
              SmartDialog.showToast("验证码、账号信息不能为空");
              return;
            }

            print(code);
            print(accountMsg);
            print(uuid);

            var rp = await DioHttp.post(Api.DAMAI_LOGIN_API, {
              "username": accountMsg['userName'],
              "password": accountMsg['pwd'],
              "code": code,
              "uuid": uuid,
            });
            print(rp);

            if (rp == null || rp['token'] == null) {
              SmartDialog.showToast(rp['msg'] ?? "登录失败");
              return;
            }

            controller.saveAuthorization("Bearer " + rp['token']);

            SmartDialog.showToast("成功");
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: const Text('取消'),
          onPressed: () async {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}
